<template>
	<view class="content1">
		<view class="tabNav">
			<view :class="{'active':curTab== index}" class="view" v-for="(item,index) in tabList" :key="index" @click="checkTab(index)">{{item.name}}</view>
		</view>
		<view class="content">
			<scroll-view
				refresher-enabled="true"
				@refresherrefresh="onDownRefresh"
				style="height: 100%"
				:refresher-triggered="isRefreshing"
				@scrolltolower="loadMore"
				:onLoadmore="false"
				v-if="curTab == 0"
				scroll-y="true">
				<view class="listBox">
					<view class="list" v-for="(item, index) in data.dataList" :key="item.id">
						<view class="info flex" style="justify-content: space-between;" @click.native.stop="goDetail(item)">
							<view class="address">{{item.apartmentName|| '--'}}{{item.roomName|| '--'}}</view>
							<uni-icons class="icon" type="forward" size="18" color="#6A6A6A"></uni-icons>
						</view>
						<view  @click="openPopup(item)">
							<view class="intro flex">
								<view class="tit">合同周期：</view>
								<view class="txt flex-1 text-right">{{timestamp(item.startTime)|| '--'}}-{{timestamp(item.endTime)|| '--'}}</view>
							</view>
							<view class="intro flex">
								<view class="tit">租客名称：</view>
								<view class="txt flex-1 text-right">{{item.customerName|| '--'}}</view>
							</view>
							<view class="intro flex">
								<view class="tit">租金：</view>
								<view class="txt flex-1 text-right"><text class="yellow">{{item.monthRent|| '--'}}元</text>/月</view>
							</view>
							<view class="intro flex">
								<view class="tit">时间：</view>
								<view class="txt flex-1 text-right">{{timestamp(item.createTime,'s')|| '--'}}</view>
							</view>
							<view class="status">
								<view :class="{
									'green':['check_in','active'].includes(item.contractStatus),
									'blue':['active','no_signed'].includes(item.contractStatus)}">{{computedStatus(item.contractStatus)}}</view>
								<view @click.native.stop="confirmStay(item)" v-if="item.stayFlag" class="stay">交房确认</view>
							</view>
						</view>
						<view class="btn center" v-if="item.contractStatus != 'lost_effectiveness'">
							<text class="yellow" v-if="item.contractStatus == 'no_signed'&&item.signStatus == 'signed_party_b'&&item.signType != 1" @click.native.stop="goSign(item)">在线签约</text>
							<text class="yellow" v-if="['check_in','active'].includes(item.contractStatus)" @click.native.stop="downLoadContract(item)">下载电子合同</text>
						</view>
					</view>
					<view v-if="!data.dataList || data.dataList&&data.dataList.length == 0" class="flex-b">
						<u-empty mode="data" icon="https://www.mescroll.com/img/mescroll-empty.png"></u-empty>
					</view>
				</view>
			</scroll-view>
			<scroll-view
				refresher-enabled="true"
				@refresherrefresh="onDownRefresh"
				style="height: 100%"
				:refresher-triggered="isRefreshing"
				@scrolltolower="loadMore"
				:onLoadmore="false"
				v-if="curTab == 1"
				scroll-y="true">
				<view class="listBox2">
					<view class="list" v-if="data.dataList&&data.dataList.length > 0" v-for="(item,index) in data.dataList" :key="index" @tap="goApplyDetail(item)">
						<view class="info flex" @click.stop="show = true">
							<view class="address flex-1">{{item.roomName|| '--'}}</view>
							<view class="btn" v-if="item.applyType == 1">退租申请</view>
							<view class="btn" v-if="item.applyType == 2">续租申请</view>
							<view class="btn" v-if="item.applyType == 3">延期申请</view>
						</view>
						<view class="intro flex">
							<view class="tit">合同周期：</view>
							<view class="txt flex-1 text-right">{{timestamp(item.sourceStartTime)|| '--'}}-{{timestamp(item.sourceEndTime)|| '--'}}</view>
						</view>
						<view class="intro flex">
							<view class="tit">租客名称：</view>
							<view class="txt flex-1 text-right">{{item.customerName || '--'}}</view>
						</view>
						<view class="intro flex">
							<view class="tit">申请时间：</view>
							<view class="txt flex-1 text-right">{{timestamp(item.applyTime,'s')|| '--'}}</view>
						</view>
						<view class="intro flex">
							<view class="tit">申请状态：</view>
							<view class="txt flex-1 text-right blue">
								{{item.applyStatusStr}}
							</view>
						</view>
					</view>
					<view class="flex-b" v-else>
						<u-empty mode="data" icon="https://www.mescroll.com/img/mescroll-empty.png"></u-empty>
					</view>
				</view>
			</scroll-view>
		</view>
	</view>
	<uni-popup ref="checkpopup" type="bottom" background-color="rgba(0,0,0,0)">
		<view class="check-popup">
			<view class="cancel" @click="cancel">取消</view>
			<view>
				<picker-view indicator-style="50px" :value="value" @change="bindChange" class="picker-view">
				    <picker-view-column>
				        <view class="item" v-for="(item,index) in columns" :key="index">{{item}}</view>
				    </picker-view-column>
				</picker-view>
			</view>
			<view class="btn" @click="confirm">确定</view>
		</view>
	</uni-popup>
</template>

<script setup lang="ts">
import { getContractList, downLoadElectronic, getContractApplyList } from '@/common/API/contract'
import {onShow, onLoad, onBackPress, onUnload} from "@dcloudio/uni-app"
import { reactive,ref } from "vue";
import dayjs  from "dayjs"
import config from '@/utils/config'

const curTab = ref(0)
const data = reactive({
	dataList:[]
})
const flag = ref(false)
const form = reactive({
	pageSize:10,
	pageNo:1,
	page:0,
	checkItem: null
})
const refreshIfNeeded = ref(false)
const show = ref(false)
const value = ref([0])
const columns = reactive(['申请退租', '申请续租'])
const tabList = reactive([
	{ name: '我的合同' },
	{ name: '我的申请' }
])
const checkpopup = ref(true)
const isRefreshing= ref(false)
const isLoadMore = ref(false)

const bindChange = (e) =>{
	value.value = e.detail.value
}
const openPopup = (item) => {
	if(!['check_in','active'].includes(item.contractStatus)){
		return
	}
	form.checkItem = item
	checkpopup.value.open()
}
const cancel = () => {
	form.checkItem = null
	checkpopup.value.close()
}
//确认
const confirm = () => {
	checkpopup.value.close()
	if(value.value[0] == 0){//退租
		uni.navigateTo({
			url:`ConQuit?info=${encodeURIComponent(JSON.stringify(form.checkItem))}`
		})
	}else if(value.value[0] == 1){//续租
		uni.navigateTo({
			url:`ConRenewal?info=${encodeURIComponent(JSON.stringify(form.checkItem))}`
		})
	}else if(value.value[0] == 2){//延期
		uni.navigateTo({
			url:`ConExtension?info=${encodeURIComponent(JSON.stringify(form.checkItem))}`
		})
	}
}
const checkTab = (e) =>{
	console.log(e)
	curTab.value = e;
	data.dataList = []
	form.pageSize = 10
	form.pageNo = 1
	form.page = 0
	getList()
}
const goApplyDetail = (item) => {
	if(item.applyType == 1){//退租
		uni.navigateTo({
			url: `/pages/personal/contract/ConQuitDetail?id=${item.id}`
		})
	}else if(item.applyType == 2){//续租
		uni.navigateTo({
			url: `/pages/personal/contract/ConRenewalDetail?id=${item.id}`
		})
	}else if(item.applyType == 3){//延期
		uni.navigateTo({
			url: `/pages/personal/contract/ConExtensionDetail?id=${item.id}`
		})
	}
}
const getList = async  () => {
	uni.showLoading({
		title:'加载中...'
	});
	if(curTab.value == 0){
		let res = await getContractList(form.pageSize, form.pageNo)
		console.log(res)
		uni.hideLoading()
		form.page = res.total? Math.ceil(res.total/form.pageSize) : 1
		if(res){
			data.dataList = [...data.dataList,...res.list]
		}
	}else{
		let res = await getContractApplyList(form.pageSize, form.pageNo)
		console.log(res)
		uni.hideLoading()
		form.page = res.total? Math.ceil(res.total/form.pageSize) : 1
		if(res){
			data.dataList = [...data.dataList,...res.list]
		}
	}
}
const goDetail = (item) => {
	uni.navigateTo({
		url:`/pages/personal/contract/detail/index?id=${item.id}&stayFlag=${item.stayFlag}`
	})
}
//在线签约
const goSign = (item) => {
	let userInfo = uni.getStorageSync('userInfo')
	if(!userInfo.authenticated){
		uni.showToast({
			title: '用户未实名认证',
			icon: 'none',
		});
		return
	}
	// #ifdef APP-PLUS
	console.log("plus");

	plus.share.getServices(function(res){
		var sweixin = null;
		for (var i = 0; i < res.length; i++) {
			var t = res[i];
			if (t.id == 'weixin') {
				sweixin = t;
			}
		}
		console.log(JSON.stringify(sweixin))
		let loginInfo = {
			userPhone: uni.getStorageSync('userPhone'),
			accessToken: uni.getStorageSync('accessToken'),
			userId: uni.getStorageSync('userId'),
			tenentId: uni.getStorageSync('tenentId')
		}
		if (sweixin) {
			sweixin.launchMiniProgram({
				id: config.wxChatAppId,
				type: config.type,
				path: `/pages/internal/index?loginInfo=${encodeURIComponent(JSON.stringify(loginInfo))}&url=${encodeURIComponent(`/pages/personal/contract/contractSign?id=${item.id}&phone=${item.customerPhone}`)}`
			});
		}
	}, function(e){
	    console.log();
	});
	//#endif

	// #ifndef APP-PLUS
		uni.redirectTo({
			url:`/pages/personal/contract/contractSign?id=${item.id}&phone=${item.customerPhone}`
		})
	// #endif
}
//状态
const computedStatus = (val:string) => {
	switch(val){
		case 'pending':
			return '待审批'
		case 'no_signed':
			return '待签约'
		case 'active':
			return '已生效'
		case 'abnormal_end':
			return '非正常结束'
		case 'check_in':
			return '已入住'
		case 'reject':
			return '审批驳回'
		case 'normal_end':
			return '正常结束'
		case 'nullify':
			return '合同作废'
		case 'lost_effectiveness':
			return '已失效'
		default:
			return '--'
	}
}
onShow(()=>{
	form.pageNo = 1
	form.pageSize = 10
	data.dataList = [];
	getList()
	// if (refreshIfNeeded.value) {
	// 	refreshIfNeeded.value = false;
	// 	data.dataList = [];
	// 	// getList();
	// }
})
onLoad((options)=>{
	if(options){
		flag.value = options.flag
	}
	// getList()
})
const onDownRefresh = () => {
	data.dataList = []
	console.log('下拉刷新')
	form.pageNo = 1
	form.pageSize = 10
    isRefreshing.value = true;
	getList()
    setTimeout(() => {
        isRefreshing.value = false;
        uni.stopPullDownRefresh()
    }, 800)
}
const loadMore = () => {
	console.log('上拉加载更多')
	if(form.pageNo > form.page){
		return
	}
	form.pageNo ++
    isLoadMore.value = true;
	getList()
    setTimeout(() => {
		isLoadMore.value = false;
    }, 2000)
}
//处理时间戳
const timestamp = (val:any,s) => {
	return val? (!s ? dayjs(val).format('YYYY-MM-DD') : dayjs(val).format('YYYY-MM-DD HH:mm:ss')) : '--'
}
//监听返回按钮
onBackPress((options)=>{
	// if(options.from == 'backbutton'){
	// 	console.log('backbutton')
	// 	uni.switchTab({
	// 	    url: '/pages/personal/index',
	// 	})
	// }
})
onUnload(()=>{
	console.log('onUnload')
	if(!flag.value){
		uni.switchTab({
		    url: '/pages/personal/index',
		})
	}
})
//交房确认
const confirmStay = (item) => {
	uni.navigateTo({
		url:`/pages/personal/contract/detail/confirmation?id=${item.id}`
	})
}
//下载电子合同
const downLoadContract = async (item) => {
	let p = await downLoadElectronic(item.id)
	if(p){
		// #ifdef MP-WEIXIN
		uni.downloadFile({
			url: p.downloadUrl,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: (res1) => {
						  var savedFilePath = res1.savedFilePath;
						  if(savedFilePath){
							wx.openDocument({
								filePath: res1.savedFilePath,
								showMenu: true,
								fileType: "pdf",
								success: function (res2) {
									console.log('打开PDF成功');
								},
								fail:function(err){
									console.log(err)
								}
							})
						  }
						},fail: err2 => {
							console.log(err2)
						}
					})
				}
			},
			fail:(err1) => {
				console.log(err1)
			}
		});
		// #endif

		// #ifdef APP-PLUS
		 uni.downloadFile({
		   url: p.downloadUrl,
		   success: res => {
		     console.log(res)
		     if (res.statusCode === 200) {
		       uni.saveFile({
		         tempFilePath: res.tempFilePath,
		         success:res2 => {
					uni.openDocument({
						filePath: res2.savedFilePath,
						showMenu: true,
						fileType: "pdf",
						success: function (res3) {
							console.log('打开PDF成功');
						},
						fail: function (err) {
							if(err.errCode == 1 || err.code == 1){
								// uni.showToast({
								// 	title: `未找到能打开PDF类型文件的手机应用`,
								// 	icon: 'none'
								// })
								uni.navigateTo({
									url: `/pages/personal/contract/web-view?url=${encodeURIComponent(p.downloadUrl)}`
								})
							}
						}
					})
		         },
		         fail: e => {
				  console.log(e)
		           uni.showToast({
		             title: "保存失败，请稍后重试！",
		             icon: "none"
		           })
		         }
		       })
		     }
		   },fail:err=>{
			   console.log(err)
		   }
		 })
		 // #endif
	}
}
</script>
<style>
	page{
		height: 100%;
	}
</style>
<style lang="scss" scoped>
.content1{
	display: flex;
	flex-direction: column;
	height: 100%;
	overflow: hidden;
}
.tabNav{
	display: flex;
	flex-direction: row;
	justify-content: space-around;
	background: #fff;
	.view{
		padding: 20rpx 0;
	}
	.active{
		color: #FD9618;
		position: relative;
		&::before{
			content: " ";
			position: absolute;
			left: 50%;
			transform: translateX(-24rpx);
			bottom: 0;
			width: 48rpx;
			height: 4rpx;
			border-top: 4rpx solid rgba(253, 150, 24, 1);
		}
	}
}
.content {
	flex: 1;
	overflow: hidden;
	.listBox{
		padding: 24rpx 32rpx;
		.list{
			background: #fff;
			margin: 0 0 24rpx;
			border-radius: 8rpx;
			padding: 36rpx 32rpx 0;
			box-shadow: 0px 0px 16px rgb(255, 255, 255, 0.08);
			.info{
				margin: 0 0 20rpx;
				.address{
					font-weight: 400;
					font-size: 36rpx;
					line-height: 44rpx;
					width: 400rpx;
					text-overflow: ellipsis;
					white-space: nowrap;
					overflow: hidden;
					display: inline-block;
				}
				.icon{
					line-height: 44rpx;
				}
			}
			.intro{
				margin: 0 0 10rpx;
				.tit,.txt{
					color: #999;
					line-height: 44rpx;
				}
			}
			.status{
				color: #ccc;
				font-size: 32rpx;
				line-height: 38rpx;
				padding: 6rpx 0 24rpx;
			}
			.btn{
				border-top: 2rpx solid #E5E5E5;
				padding: 30rpx 0;
			}
		}
	}
	.listBox2{
		padding: 24rpx 32rpx;
		.list{
			background: #fff;
			margin: 0 0 24rpx;
			border-radius: 8rpx;
			padding: 32rpx 32rpx 28rpx;
			box-shadow: 0px 0px 16px rgb(255, 255, 255, 0.08);
			.info{
				margin: 0 0 20rpx;
				.address{
					font-weight: 400;
					font-size: 36rpx;
					line-height: 44rpx;
					width: 400rpx;
					text-overflow: ellipsis;
					white-space: nowrap;
					overflow: hidden;
					display: inline-block;
				}
				.btn{
					width: 160rpx;
					height: 56rpx;
					line-height: 56rpx;
					border-radius: 8rpx;
					border: 2rpx solid $uni-color-primary;
					text-align: center;
					color: $uni-color-primary;
				}
			}
			.intro{
				margin: 0 0 10rpx;
				.tit,.txt{
					color: #999;
					line-height: 44rpx;
				}
			}
		}
	}
}
.text-right{
	text-align: right;
}
.gray{
	color:rgba(204, 204, 204, 1)
}
.blue{
	color: rgba(49, 113, 232, 1);
}
.flex-b{
	display: flex;
	align-items: center;
	justify-content: center;
}
.status{
	display: flex;
	justify-content: space-between;
	.stay{
		color: rgba(253, 150, 24, 1);
	}
}
.check-popup{
	height: 530rpx;
	border-radius: 28rpx 28rpx 0 0;
	background: rgba(255, 255, 255, 1);
	text-align: center;
	.picker-view{
		height: 200rpx;
	}
	.cancel{
		color: rgba(153, 153, 153, 1);
		font-size: 26rpx;
		text-align: right;
		padding: 32rpx;
	}
	.btn{
		margin: 94rpx 32rpx 40rpx 32rpx;
		border-radius: 200rpx;
		background: rgba(253, 150, 24, 1);
		color: #fff;
		border-radius: 200rpx;
		height: 84rpx;
		line-height: 84rpx;
		font-size: 32rpx;
	}
}
</style>
